package com.smasher.doc.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.WindowManager
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.splashscreen.SplashScreenViewProvider
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.smasher.core.other.WeakReferenceHandler
import com.smasher.core.utils.DensityUtil
import com.smasher.doc.BuildConfig
import com.smasher.doc.databinding.ActivitySplashBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean

@SuppressLint("CustomSplashScreen")
class SplashActivity : AppCompatActivity() {

    /**
     * 控制是否保持启动页面的变量,值为false时继续往下走
     */
    private val keepOnScreenCondition = AtomicBoolean(true)

    private val dialogShowInvoke = AtomicBoolean(false)

    private lateinit var mBinding: ActivitySplashBinding

    private val debug = BuildConfig.DEBUG

    private val callback = Handler.Callback {
        return@Callback false
    }

    private val mHandler by lazy {
        WeakReferenceHandler(callback)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val controller = WindowCompat.getInsetsController(window, window.decorView)
        controller.hide(WindowInsetsCompat.Type.statusBars())

        settingCutPlayMode()
        settingFullScreen()
        logScreenSize()

        //处理splash screen过渡
        installSplashScreen().apply {
            setKeepOnScreenCondition {
                //一直停留在SplashScreen启动界面
                keepOnScreenCondition.get()
            }
            setOnExitAnimationListener { splashScreenView: SplashScreenViewProvider ->
                splashScreenView.remove()
                Log.d(TAG, "OnExitAnimation: ")
                showPrivacyPolicy()
            }
        }

        mBinding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        lifecycleScope.launch {

            Log.i("SplashActivity", "可以做一些初始化逻辑")
            /*解除 block UI，此时正常情况下会调用setOnExitAnimationListener 已知Android12拉起App时不会调用*/
            keepOnScreenCondition.compareAndSet(true, false)
            delay(100)//这里最好延迟一下，保证setOnExitAnimationListener有机会得到执行
            if (!dialogShowInvoke.get()) {
                showPrivacyPolicy()//这里去掉调用一下最终要执行的方法，兜个底
            }
        }
    }

    private fun logScreenSize() {
        val dm = resources.displayMetrics
        val densityDpi = dm.densityDpi
        val widthPixels = dm.widthPixels
        val heightPixels = dm.heightPixels
        Log.d("SPLASH", "==================================================")
        Log.d("SPLASH", "densityDpi=$densityDpi")
        Log.d("SPLASH", "widthPixels=$widthPixels")
        Log.d("SPLASH", "heightPixels=$heightPixels")
        Log.d("SPLASH", "widthDP=" + DensityUtil.px2dip(widthPixels.toFloat()))
        Log.d("SPLASH", "heightDP=" + DensityUtil.px2dip(heightPixels.toFloat()))
        Log.d("SPLASH", "==================================================")
    }

    private fun settingFullScreen() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
    }

    private fun settingCutPlayMode() {
        val window = window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val lp = window.attributes

            // 仅当缺口区域完全包含在状态栏之中时，才允许窗口延伸到刘海区域显示//
            //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT;
            // 永远不允许窗口延伸到刘海区域//
            //lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
            //允许window 的内容可以上移到刘海屏状态栏
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = lp
        }
    }

    private fun showPrivacyPolicy() {
        if (dialogShowInvoke.get()) {/*已经执行了*/
            return
        }
        dialogShowInvoke.compareAndSet(false, true)

        gotoMain()
    }

    private fun gotoMain() {
        startActivity(Intent().apply {
            setClass(this@SplashActivity, HomeActivity::class.java)
        })
        finish()
    }

    override fun onDestroy() {
        mHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    private val splashLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            val code = it.resultCode
            if (code == RESULT_OK) {
                gotoMain()
            }
            finish()
        }


    //==============================================


    companion object {
        const val TAG = "SPLASH"
    }
}